package com.fudan.gamestore.controller;

import com.fudan.gamestore.pojo.*;
import com.fudan.gamestore.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private GameService gameService;
    @Autowired
    private CartService cartService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AlipayService alipayService;

    @RequestMapping(value = "/user/order/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getOrderByUserIdPage(@PathVariable("userId") Integer userId,
                                                    @RequestParam(name = "size") Integer size,
                                                    @RequestParam(name = "current") Integer current,
                                                    @RequestHeader String token) {
        Map<String, Object> retMap = new HashMap<>();
        if (tokenService.checkToken(token, userId, 0) < 0) {
            retMap.put("status", 400);
            retMap.put("info", "未授权");
            return retMap;
        }

        PageInfo<Order> orderPageInfo = orderService.getOrderByUserIdPage(userId, size, current);
        retMap.put("orderList", orderPageInfo.getList());
        retMap.put("total", orderPageInfo.getTotal());
        retMap.put("current", current);
        retMap.put("status", 200);
        retMap.put("info", "success");
        return retMap;
    }

    @RequestMapping(value = "/allOrders", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getAllOrder(Integer size, Integer current, @RequestHeader String token) {
        Map<String, Object> retMap = new HashMap<>();
        if (tokenService.checkToken(token, -1, 1) < 0) {
            retMap.put("status", 400);
            retMap.put("info", "未授权");
            return retMap;
        }
        PageInfo<Order> page = orderService.getAllOrderByPage(size, current);
        retMap.put("orderList", page.getList());
        retMap.put("total", page.getTotal());
        retMap.put("current", current);
        retMap.put("status", 200);
        retMap.put("info", "success");
        return retMap;
    }

    @RequestMapping(value = "/order/confirm", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> confirmOrder(@RequestBody Map<String, Object> map, @RequestHeader String token) {
        int userId = (int) map.get("userId");
        Map<String, Object> retMap = new HashMap<>();
        if (tokenService.checkToken(token, userId, 0) < 0) {
            retMap.put("status", 400);
            retMap.put("info", "未授权");
            return retMap;
        }
        List<Integer> buyGameList = (List<Integer>) map.get("gameList");
        User user = userService.getUserById(userId);
        int orderId;

        if (user == null) {
            retMap.put("status", 500);
            retMap.put("info", "user not found");
            return retMap;
        }
        //判断是否已拥有
        Map<Integer, Integer> buyGameListMap = new HashMap<>();
        for (Integer i : buyGameList)
            buyGameListMap.put(i, 1);
        List<Game> games;
        if ((games = gameService.getOwnGameByUserId(userId)) != null) {
            for (Game game : games) {
                if (buyGameListMap.get(game.getGameId()) != null) {
                    retMap.put("status", 500);
                    retMap.put("info", "user has owned");
                    retMap.put("orderId", -1);
                    return retMap;
                }
            }
        }
        //删除对应购物车条目
        cartService.deleteCartItems(userId, buyGameList);

        if ((orderId = orderService.insertOrder(userId, buyGameList)) >= 0) {
            retMap.put("status", 200);
            retMap.put("info", "success");
            retMap.put("orderId", orderId);
            return retMap;
        }

        retMap.put("status", 500);
        retMap.put("info", "failed");
        return retMap;
    }

    @RequestMapping(value = "/order/delete", method = RequestMethod.POST)
    @ResponseBody
    public Response deleteOrder(@RequestBody Map<String, Object> map, @RequestHeader String token) {
        int orderId = (int) map.get("orderId");
        Order order = orderService.getOrderByOrderId(orderId);
        if (order == null) {
            return new Response(400, "订单不存在");
        }
        if (tokenService.checkToken(token, order.getUserId(), 0) < 0) {
            return new Response(400, "未授权");
        }
        if (orderService.deleteOrderByOrderId(orderId) > 0) {
            return new Response(200, "success");
        }
        return new Response(500, "delete failed");
    }

    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> payOrder(@RequestBody Map<String, Object> map, @RequestHeader String token) {
        Map<String, Object> retMap = new HashMap<>();

        int orderId = (Integer) map.get("orderId");
        Order order = orderService.getOrderByOrderId(orderId);
        if (order == null) return null;
        if (tokenService.checkToken(token, order.getUserId(), 0) < 0) {
            retMap.put("status", 500);
            retMap.put("info", "未授权");
            retMap.put("pageContent", null);
            return retMap;
        }
        User user = userService.getUserById(order.getUserId());

        //判断是否已拥有游戏
        Map<Integer, Integer> buyGameListMap = new HashMap<>();
        for (OrderItem item : order.getOrderItemList())
            buyGameListMap.put(item.getGameId(), 1);
        List<Game> games;
        if ((games = gameService.getOwnGameByUserId(order.getUserId())) != null) {
            for (Game game : games) {
                if (buyGameListMap.get(game.getGameId()) != null) {
                    retMap.put("status", 500);
                    retMap.put("info", "user has owned the game");
                    retMap.put("pageContent", null);
                    return retMap;
                }
            }
        }

        String result = null;
        //支付接口
        try {
            result = alipayService.toAlipay(user.getUsername(), orderId, order.getOrderMoney());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (result != null) {
            retMap.put("status", 200);
            retMap.put("info", "success, forwarding to alipay");
            retMap.put("pageContent", result);
            return retMap;
        }

        retMap.put("status", 400);
        retMap.put("info", "alipay error");
        retMap.put("pageContent", null);
        return retMap;
    }
}
